import { useEventListener } from '@vueuse/core'
import {
	DragEvent,
	Leafer,
	Pen,
	ZoomEvent,
	LeafHelper,
	RotateEvent,
	ImageManager
} from 'leafer-ui'
import '@leafer-in/viewport'
import '@leafer-in/view'
import '@leafer-in/animate'
export const useWhiteBoard = (config: { id: string }) => {
	let app: Leafer
	let isDrawing = false
	let pen: Pen
	const scale = ref(1)
	const color = ref('#C40833')
	const startPen = ref(false)
	let fitScale = 1
	const startDrawing = (e: DragEvent) => {
		if (e?.multiTouch) return (isDrawing = false)
		if (startPen.value) {
			isDrawing = true
			const point = e.getPagePoint()
			pen.setStyle({
				stroke: color.value,
				strokeWidth: 1 || 3 || 10,
				strokeCap: 'round',
				strokeJoin: 'round'
			})
			pen.moveTo(point.x, point.y)
		}
	}

	const continueDrawing = (e: DragEvent) => {
		if (e?.multiTouch) return (isDrawing = false)
		if (isDrawing && startPen.value) {
			const point = e.getPagePoint()
			pen.lineTo(point.x, point.y)
		}
	}

	const stopDrawing = (e: DragEvent) => {
		if (isDrawing && startPen.value) {
			isDrawing = false
			app.off(DragEvent.DRAG, dragDragHandler)
			app.off(DragEvent.END, stopDrawing)
		}
	}

	const dragDragHandler = (e: DragEvent) => {
		continueDrawing(e)
	}
	const initPen = () => {
		if (pen) {
			app.remove(pen)
		}
		pen = new Pen()
		app.add(pen)
	}
	const init = () => {
		app = new Leafer({
			view: config.id,
			smooth: true,
			pointer: { touch: true },
			touch: { preventDefault: true },
			type: 'design',
			hittable: false,
			move: {
				scroll: false
			},
			usePartRender: false
		})

		app.on(ZoomEvent.ZOOM, function () {
			scale.value = +app.scale / fitScale
		})
		app.on(DragEvent.START, (e: DragEvent) => {
			if (startPen.value) {
				startDrawing(e)
				app.on(DragEvent.DRAG, dragDragHandler)
				app.on(DragEvent.END, stopDrawing)
			}
		})
		//双指旋转
		app.on(RotateEvent.ROTATE, function (e: RotateEvent) {
			const center = { x: e.x, y: e.y }
			LeafHelper.rotateOfWorld(app, center, e.rotation)
		})
		initPen()
	}

	const clear = () => {
		pen.clear()
	}

	watch(
		() => startPen.value,
		() => {
			app.hittable = startPen.value
		}
	)
	onMounted(() => {
		init()
	})
	useEventListener('unload', () => {
		const { list } = Leafer
		list.forEach((leafer) => (leafer as Leafer).destroy(true))
		list.destroy()
		ImageManager.destroy()
	})
	const destroy = () => {
		app.destroy()
	}
	return {
		clear,
		scale,
		startPen,
		color,
		destroy
	}
}
